const gulp = require('gulp');
const htmlMin = require('gulp-htmlmin');
const cssMin = require('gulp-cssmin')
const autoPrefixer = require('gulp-autoprefixer')
const sass = require('gulp-sass');
const uglify = require('gulp-uglify');
const babel = require('gulp-babel');
const clean = require('gulp-clean');
const fileInclude = require('gulp-file-include');
const runSequence = require('run-sequence');
const webserver = require('gulp-webserver');
const watch = require('gulp-watch');
/* 
参数一，任务名称
参数二，任务做什么
*/
//打包html
gulp.task('html', function () {
  //对哪些文件进行处理
  return gulp.src('./src/html/**')
    .pipe(fileInclude({
      basepath: './src/components',
      prefix: '@@'
    }))
    .pipe(
      htmlMin({
        minifyCSS: true,    //去除css的样式空格
        minifyJS: true,     //去除js的样式空格
        removeEmptyAttributes: true,    //去除空属性
        removeComments: true,     //去除注释
        removeScriptTypeAttributes: true,     //去除script标签内空属性
        collapseWhitespace: true       // 去除空白行
      })
    ).pipe(gulp.dest('./dist/html'))  // 把压缩后的html存到处理后文件夹
})
//打包并编译sass
gulp.task('sass', function () {
  return gulp.src('./src/css/**')
    .pipe(sass())
    .pipe(autoPrefixer())   //自动补全前缀，浏览器css兼容
    .pipe(cssMin())
    .pipe(gulp.dest('./dist/css'))
})
//打包js
gulp.task('js', function () {
  return gulp.src('./src/js/**')
    .pipe(babel({
      presets: ['es2015']
    }))
    .pipe(uglify())
    .pipe(gulp.dest('./dist/js'))
})
//打包库文件
gulp.task('lib', function () {
  return gulp.src('./src/lib/**')
    .pipe(gulp.dest('./dist/lib'))
})
//打包静态资源
gulp.task('static', function () {
  return gulp.src('./src/static/**')
    .pipe(gulp.dest('./dist/static'))
})
//删除dist文件夹
gulp.task('clean', function () {
  return gulp.src('./dist')
    .pipe(clean())
})

//打开浏览器
gulp.task('open', function () {
  return gulp.src('./dist')
    .pipe(webserver({
      host: 'localhost',
      port: 8080,
      livereload: true,
      open: './html/index.html'
    }))
})

//监听文件变化，热加载
gulp.task('watch', function () {
  /* watch('./src/html', function () {
    gulp.start('html');
    // browserSync.reload();
  }) */

  gulp.watch('./src/html/*.html', ['html'])
  gulp.watch('./src/css/*.scss', ['sass'])
  gulp.watch('./src/js/*.js', ['js'])
  gulp.watch('./src/lib/**', ['lib'])
})
//一键执行
// ['clean']不执行的话，后面的任务也不会执行
gulp.task('default', ['clean'], function () {
  runSequence(['html', 'sass', 'lib', 'js','static'], 'open', 'watch')
})